package com.laundry.controller.admin;

import com.laundry.dao.OrderDao;
import com.laundry.dto.ResultDTO;
import com.laundry.entity.Order;
import com.laundry.service.OrderService;
import com.laundry.vo.OrderVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;

@RestController
@RequestMapping("/api/admin/order")
public class AdminOrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderDao orderDao;

    @GetMapping("/list")
    public ResultDTO getOrderList(@RequestParam(required = false) String orderNo,
                                @RequestParam(required = false) Integer status,
                                @RequestParam(required = false) Integer limit) {
        try {
            List<Order> orders;
            
            // 根据参数筛选订单
            if (orderNo != null && !orderNo.isEmpty() && status != null) {
                // 同时按订单号和状态搜索
                orders = orderService.findByOrderNoAndStatus(orderNo, status);
            } else if (orderNo != null && !orderNo.isEmpty()) {
                // 只按订单号搜索，但支持模糊搜索
                orders = orderDao.findByOrderNoContaining(orderNo);
            } else if (status != null) {
                // 只按状态搜索
                orders = orderService.findByStatus(status);
            } else {
                // 无搜索条件，返回所有订单
                orders = orderService.getAllOrders();
            }
            
            // 如果指定了limit参数，则限制返回数量
            if (limit != null && limit > 0 && orders.size() > limit) {
                orders = orders.subList(0, limit);
            }
            
            // 转换为OrderVO
            List<OrderVO> orderVOs = orderService.convertToOrderVOList(orders);
            
            return ResultDTO.success(orderVOs);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultDTO.error("获取订单列表失败：" + e.getMessage());
        }
    }

    @GetMapping("/{id}")
    public ResultDTO getOrderDetail(@PathVariable Long id) {
        OrderVO orderVO = orderService.getOrderDetail(id);
        if (orderVO == null) {
            return ResultDTO.error("订单不存在");
        }
        return ResultDTO.success(orderVO);
    }
    
    @PutMapping("/updateStatus")
    public ResultDTO updateOrderStatus(@RequestParam String orderNo, @RequestParam Integer status) {
        try {
            orderService.updateOrderStatus(orderNo, status);
            return ResultDTO.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultDTO.error("更新订单状态失败：" + e.getMessage());
        }
    }
} 